<template>
    <base-dialog :dialogObj="fieldsSortDialog" class="base-dialog" v-on="$listeners">
        <template v-slot:content>
            <p v-if="showCondition" class="sort-header">
                <el-checkbox v-model="saveAsSystem"> 存为系统配置 </el-checkbox>
            </p>
            <base-table
                ref="draggableTable"
                :tableData="customFieldsList"
                :colunmData="fieldsColumn"
                class="sort-table"
                :tableConfig="{
                    isIndex: false,
                    isMultiSelect: false,
                    isShowOpera: false,
                    height: '300px'
                }"
            >
                <!-- <template v-slot>
          <svg-icon
            name="rank_btn"
            className="w18 h14 hover-move" />
        </template> -->
                <template v-slot:tableCell="{ scope: { row, item } }">
                    <template v-if="item.type === 'image'">
                        <svg-icon name="rank_btn" className="w18 h14 hover-move" />
                    </template>
                    <template>
                        <span class="pdl-10">{{ row[item.value] }}</span>
                    </template>
                </template>
            </base-table>
        </template>
        <template v-slot:footerBtn>
            <div class="button-list">
                <el-button v-for="(item, index) in buttonConfig" :key="index" :type="item.type" @click="item.event">
                    {{ $t(item.name) }}
                </el-button>
            </div>
        </template>
    </base-dialog>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { DialogObj } from '@/typings';
import { Prop } from 'vue-property-decorator';
import { TableHeaderConfig } from '@/typings';
// import commonApi from '@/api/common-api'
// import draggable from 'vuedraggable'
import Sortable from 'sortablejs';
const requestApi = {
    getBillColumnListBySystem: '/information/billColumnSetting/getBillColumnListBySystem',
    list: '/information/billColumnSetting/list',
    update: '/information/billColumnSetting/update'
};
@Component({
    name: 'fields-sort',
    components: {
        // draggable,
        baseDialog: () => import('@/components/base-dialog/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue')
    }
})
export default class App extends Vue {
    @Prop({ required: true }) fieldsList: any[];
    // 默认请求参数
    @Prop({
        default: () => {
            return {};
        }
    })
    defaultRequest;
    fieldsSortDialog: DialogObj = {
        title: '',
        isShowDialog: false,
        appendToBody: true,
        width: '680px'
    };
    saveAsSystem: boolean = false;
    fieldsColumn: TableHeaderConfig[] = [
        {
            label: '序号',
            value: 'index',
            width: '60px',
            lang: 'reportCommonWord.index'
        },
        {
            label: '字段',
            value: 'columnTitle',
            lang: 'reportCommonWord.fields'
        },
        {
            label: '操作',
            value: 'operation',
            type: 'image',
            align: 'center',
            lang: 'layout.btns.operation'
        }
    ];
    sortable: Sortable | null = null;
    // 按钮组
    buttonConfig: any[] = [
        {
            name: 'layout.btns.cancel',
            event: this.cancel
        },
        {
            name: 'layout.btns.resetConfig',
            event: this.resetConfig
        },
        {
            type: 'primary',
            name: 'layout.btns.sure',
            event: this.confirmSort
        }
    ];
    // 自定义字段列表
    customFieldsList: any[] = [];
    // 【存为系统】显示的条件
    get showCondition() {
        // return getCookie('userNo') === 'admin'
        return this.$store.state.user.userNo === 'admin';
    }
    // 模块id
    get moduleId() {
        return this.$route.meta.moduleId;
    }
    // 取消
    cancel() {
        this.$set(this.fieldsSortDialog, 'isShowDialog', false);
    }
    // 重置配置[ 获取系统默认排序]
    async resetConfig() {
        const res = await this._post({
            url: `${requestApi.getBillColumnListBySystem}/${this.moduleId}`,
            data: {
                data: {
                    ...this.defaultRequest
                }
            }
        });
        if (res.code === 0) {
            this.$message.success('已获取系统默认配置');
            this.customFieldsList = res.data.map((item, index) => {
                return {
                    ...item,
                    index: index + 1
                };
            });
        }
    }
    // 字段的排序
    private setSort(el) {
        this.sortable = Sortable.create(el, {
            ghostClass: 'sortable-ghost', // Class name for the drop placeholder
            onEnd: (evt) => {
                if (typeof evt.oldIndex !== 'undefined' && typeof evt.newIndex !== 'undefined') {
                    const current = this.customFieldsList;
                    current.splice(evt.newIndex, 0, current.splice(evt.oldIndex, 1)[0]);
                    var newArray = this.customFieldsList.slice(0);
                    this.customFieldsList = [];
                    this.$nextTick(async function () {
                        this.customFieldsList = newArray.map((item, index) => {
                            return Object.assign(item, {
                                index: index + 1,
                                orderNumber: index + 1
                            });
                        });
                    });
                }
            }
        });
    }
    // 获取模块自定义货品列表
    async getCustomFieldsColumn() {
        this.customFieldsList.splice(0);
        const res = await this._post({
            url: requestApi.list,
            data: { data: { moduleId: this.moduleId, ...this.defaultRequest } }
        });
        if (res.code === 0) {
            this.customFieldsList = res.data.map((item, index) => {
                return {
                    ...item,
                    index: index + 1
                };
            });
        }
    }
    // 打开
    async open() {
        this.saveAsSystem = false;
        this.fieldsSortDialog.isShowDialog = true;
        this.fieldsSortDialog.title = this.$t('commonWord.fieldsSortConfig');
        await this.getCustomFieldsColumn();
        this.$nextTick(() => {
            const ref: any = this.$refs.draggableTable;
            const el = ref.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
            this.setSort(el);
        });
    }
    // 保存
    async confirmSort() {
        console.error('保存');
        const res = await this._put({
            url: requestApi.update,
            data: {
                data: {
                    billColumnSettingList: this.customFieldsList,
                    moduleId: this.moduleId,
                    systemFlag: this.saveAsSystem,
                    ...this.defaultRequest
                }
            }
        });
        if (res.code === 0) {
            this.$message.success('保存成功');
            this.$emit('confirmSort', this.customFieldsList);
            this.$set(this.fieldsSortDialog, 'isShowDialog', false);
        }
    }
}
</script>

<style scoped lang="scss">
.base-dialog {
    /deep/.el-dialog__body {
        padding: 16px;
    }
}
.base-pagetion {
    justify-content: center !important;
    /deep/.page-select {
        margin: 0 10px;
    }
}
.query-group {
    display: flex;
    align-items: center;
    &-form {
        flex: 1;
    }
    &-btn {
        // margin-left: 10px;
        margin: 5px 0 0 10px;
    }
}
.sort-list {
    border: 1px solid #eee;
    &-header,
    &-item {
        display: flex;
        color: #353d51;
        height: 28px;
        line-height: 28px;
        font-size: 12px;
        // padding: 0 10px;
        border-bottom: 1px solid #eee;
    }
    .content {
        text-align: left;
        padding: 0 10px;
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
    }
    .bg-g {
        background: #f5f5f7;
    }
}
.sort-header {
    text-align: right;
    padding-bottom: 10px;
}
.button-list {
    margin-top: 10px;
    text-align: right;
}
</style>
